<?php

namespace Models;

class Product extends Model
{
	protected $_table = 'products';

	protected $_default_filter = 'products.is_delete=0';

	public function filter($data)
	{
		if(isset($data['thumbnail'])) $data['thumbnail'] = $data['thumbnail'];
		if (isset($data['images'])) {
			$data['images'] = explode(',', $data['images']);	
		}
		
		return $data;
	}

	public function is_favorite($user_id)
	{
		return Favorite::where([
			'user_id' => $user_id,
			'product_id' => $this['id']])->counts() > 0;
	}

	/**
	 * 修改商品库存和销售量
	 * @param  int | array $product_id 商品ID
	 * @return int                     修改数据条数
	 */
	public function stock($product_id){
		if(!is_array($product_id)) $product_id = [$product_id];
		$items = Item::select('product_id')->select_sum('stock')->select_sum('solded')->where_in('product_id',$product_id)->group_by('product_id')->get();
		$stock_arr = ['field'=>'stock','key'=>'id','data'=>[]];
		$solded_arr = ['field'=>'solded','key'=>'id','data'=>[]];
		foreach ($items as $itm) {
			$stock_arr['data'][$itm['product_id']] = $itm['stock'];
			$solded_arr['data'][$itm['product_id']] = $itm['solded'];
		}
		$where = 'id in ('.implode(',', $product_id).')';

		$result = (new Product)->multi_update([$stock_arr,$solded_arr],$where);
		return $result;
	}
}